package com.huaqin.punan.record;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	public static final String TAG = "SoundRecord_Main";
	private String recordName = "record_";
	private boolean isRecord = false;
	
	private TextView my_tv;
	private Button mBtnStart;
	private Button mBtnStop;
	
	private MediaRecorder mMeidaRecorder;
	private File file;
	private Vibrator vibrator;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		my_tv = (TextView)findViewById(R.id.my_tv);
		mBtnStart = (Button)findViewById(R.id.btn_start);
		mBtnStop = (Button)findViewById(R.id.btn_stop);
		
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

		mBtnStart.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				file = new File(Environment.getExternalStorageDirectory(), recordName + System.currentTimeMillis() + ".amr");
				mMeidaRecorder = new MediaRecorder();
				mMeidaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
				mMeidaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
				mMeidaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
				
				mMeidaRecorder.setOutputFile(file.getAbsolutePath());
				
				try {
					
					mMeidaRecorder.prepare();
					mMeidaRecorder.start();
					isRecord = true;
					Toast.makeText(getApplicationContext(), "开始录音。", Toast.LENGTH_SHORT).show(); 
					vibrator.vibrate(100);
					my_tv.setText("Recording...");
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				
			}});
		
		mBtnStop.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mMeidaRecorder != null && isRecord){
					mMeidaRecorder.stop();
					mMeidaRecorder.reset();
					mMeidaRecorder.release();
					isRecord = false;
					Toast.makeText(getApplicationContext(), "录音停止。", Toast.LENGTH_SHORT).show();
					vibrator.vibrate(100);
					my_tv.setText("stop");
				}
			}});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
